﻿
package extremefx.data {
	import extremefx.IEnumerator;	
	import extremefx.IEnumerable;	
	
	/**
	 * @author Marcelo Volmaro
	 */
	public final class Comprehension {
		public static function from(pIEnumerable:IEnumerable):Comprehension {
			return new Comprehension(pIEnumerable);
		}
		
		private var _cond:Function;
		private var _enum:IEnumerable;
		private var _retDel:Function;

		public function Comprehension(pEnum:IEnumerable) {
			_enum = pEnum;
			_retDel = _select;
			_cond = _condition;
		}
		
		public function select(pReturn:Function):Comprehension {
			_retDel = pReturn;
			return this;
		}
		
		public function where(pConditionDelegate:Function):Comprehension {
			_cond = pConditionDelegate;
			return this;
		}
		
		public function asDataSource():DataSource {
			return new DataSource(asArray());
		}
		
		public function asArray():Array {
			var filteredList:Array = [],
			enum:IEnumerator = _enum.getEnumerator(),
			idx:uint = 0;
			
			while (enum.moveNext()){
				var ds:Object = enum.current;
				if (_cond(ds)){
					filteredList[idx++] = _retDel(ds);
				}
			}
			
			return filteredList;
		}
		
		public function enumerate(pCallBack:Function):void {
			var enum:IEnumerator = _enum.getEnumerator();
			
			while (enum.moveNext()){
				var ds:Object = enum.current;
				if (_cond(ds)){
					pCallBack(_retDel(ds));
				}
			}
		}
		
		private function _condition(pDs:DSItem):Boolean {
			return true;
		}
		
		private function _select(o:DSItem):* {
			return o;
		}
	}
}
